﻿Imports HslCommunication.LogNet
Imports HslCommunication.ModBus

Public Class Form1
    Private logfile As ILogNet
    Private busClient As ModbusTcpNet 'ModbusRtu

    Private _ip As String
    Private _port As Integer
    Private _TableName As String
    Private WithEvents _timer As New Timer
    Private _errorTimes As Integer = 0

    Public Sub New()
        AddHandler AppDomain.CurrentDomain.AssemblyResolve, New ResolveEventHandler(AddressOf CurrentDomain_AssemblyResolve)

        ' 此调用是设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。

    End Sub
    Private Function CurrentDomain_AssemblyResolve(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
        Dim dllName As String = If(args.Name.Contains(","), args.Name.Substring(0, args.Name.IndexOf(","c)), args.Name.Replace(".dll", ""))
        dllName = dllName.Replace(".", "_")
        If dllName.EndsWith("_resources") Then
            Return Nothing
        End If
        Dim rm As New System.Resources.ResourceManager([GetType].Namespace & ".Resources", System.Reflection.Assembly.GetExecutingAssembly())
        Dim bytes As Byte() = DirectCast(rm.GetObject(dllName), Byte())
        Return System.Reflection.Assembly.Load(bytes)
    End Function
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        connectDB()
        logfile = New LogNetDateTime(Application.StartupPath & "\\Logs", GenerateMode.ByEveryDay)

        busClient = New ModbusTcpNet(_ip, _port, 2)
        busClient.IsStringReverse = False '字符串颠倒
        busClient.AddressStartWithZero = False '首地址从0开始
        busClient.DataFormat = HslCommunication.Core.DataFormat.ABCD
        busClient.SetPersistentConnection()

        Dim interval_Minute As Integer = 60 * 1000
        Try
            interval_Minute = CInt(getSysParam("equip_GL_interval_Minute")) * interval_Minute
        Catch ex As Exception
            logfile.WriteError(ex.Message)
        End Try

        _timer.Interval = interval_Minute

        _timer_Tick(New Object, New EventArgs)
        _timer.Start()
    End Sub

    Public Sub connectDB()
        'イニシャルファイル情報取得
        g_szInitFileName = My.Application.Info.DirectoryPath & "\setting.ini"

        g_Server.szDrive = GetIniFile("SERVER", "DRIVE", "PostgreSQL ANSI", g_szInitFileName)
        g_Server.szIPadr = GetIniFile("SERVER", "IP", "", g_szInitFileName)
        g_Server.szDbn = GetIniFile("SERVER", "DBN", "ZHENANSF", g_szInitFileName)
        g_Server.szUid = GetIniFile("SERVER", "UID", "sa", g_szInitFileName)
        g_Server.szPas = GetIniFile("SERVER", "PAS", "sa", g_szInitFileName)
        g_Server.iOver = CInt(GetIniFile("SERVER", "OVER", "-1", g_szInitFileName))

        '得到当前用户名
        g_LoginUser = GetIniFile("LOGIN", "user", "admin", g_szInitFileName)
        _ip = GetIniFile("SETTING", "address", "172.16.19.235", g_szInitFileName)
        _port = GetIniFile("SETTING", "port", "8899", g_szInitFileName)
        If False = g_fDBconnect And 0 = g_iDBconnResult Then
            If "" = g_Server.szIPadr Or "0.0.0.0" = g_Server.szIPadr Then
            Else
                g_fDBconnect = True

                'データベース接続
                With g_Server
                    g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                    If 1 <> g_iDBconnResult Then
                        .szDrive = CStr(IIf("PostgreSQL" = .szDrive, "PostgreSQL ANSI", "PostgreSQL"))
                        g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                    End If
                End With
            End If
        End If

        Dim _appType As Integer = GetIniFile("SETTING", "apptype", "1", g_szInitFileName)
        If _appType = 1 Then
            Me.Text = "锅炉房  FCM型体积修正仪 监控"
        ElseIf _appType = 2 Then
            Me.Text = "天然气  FCM型体积修正仪 监控"
        End If
        _TableName = GetIniFile("SETTING", "table", "sf.b_equip_info_guolu", g_szInitFileName)
        setAllErrMsg()
    End Sub

    Private Sub _timer_Tick(sender As Object, e As EventArgs) Handles _timer.Tick

        If _errorTimes >= 10 Then
            logfile.WriteError("重启")
            RemoveHandler Me.FormClosing, AddressOf Form1_FormClosing
            Application.Restart()
            Exit Sub
        End If
        getData()
    End Sub

    Private Sub getData()
        Try

            If busClient.ReadFloat("2").IsSuccess = False Then
                pnlStatus.BackColor = Color.Red
                logfile.WriteError("数据取得错误" & _errorTimes)
                _errorTimes = _errorTimes + 1
            Else
                pnlStatus.BackColor = Color.Green

                lblDqsj.Text = Now
                lblTotal.Text = busClient.ReadFloat("2").Content * 1000000 + busClient.ReadFloat("4").Content
                lblbiaokuang.Text = Math.Round(busClient.ReadFloat("6").Content, 2)
                lblgongkuang.Text = Math.Round(busClient.ReadFloat("8").Content, 2)
                lblwendu.Text = Math.Round(busClient.ReadFloat("10").Content, 2)
                lblyali.Text = Math.Round(busClient.ReadFloat("12").Content, 2)
                Dim msg As String = "》》" & Now & ":" & CSng(lblTotal.Text) & " \ " & CSng(lblbiaokuang.Text) & " \ " & CSng(lblgongkuang.Text) & " \ " & CSng(lblwendu.Text) & " \ " & CSng(lblyali.Text)
                lblLog.Text = msg & vbCrLf & lblLog.Text
                logfile.WriteInfo(msg)

                If insert(CSng(lblTotal.Text), CSng(lblbiaokuang.Text), CSng(lblgongkuang.Text), CSng(lblwendu.Text), CSng(lblyali.Text)) = -2 Then
                    logfile.WriteError("数据保存错误")
                End If
            End If
        Catch ex As Exception
            lblLog.Text = ex.Message & vbCrLf & lblLog.Text
            logfile.WriteError(ex.Message)
        End Try
    End Sub

    Private Function insert(zongliang As Single, biaokuang As Single, gongkuang As Single, wendu As Single, yali As Single) As Integer
        Dim szSql As String = ""
        Dim rtn As Integer

        szSql &= " INSERT INTO " & _TableName & "(savetime,zongliang,biaokuang,gongkuang,wendu,yali) VALUES (?,?,?,?,?,?)"

        rtn = DBacs.ExecuteUpdateSql(szSql, -1, Now, zongliang, biaokuang, gongkuang, wendu, yali)
        Return rtn
    End Function

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        If MsgBox("如关闭系统，则停止监控！确定要关闭吗？", 4, Me.Text) <> MsgBoxResult.Yes Then
            e.Cancel = True
        End If
    End Sub
End Class
